﻿using Microsoft.CSharp.Activities;
using System;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using WFExtended.Twitter.Activities.Designers;

namespace WFExtended.Twitter.Activities
{
    /// <summary>
    /// Updates the authenticating user's current status and attaches media for upload.
    /// </summary>
    [ToolboxBitmapAttribute(typeof(EntryPoint), "Resources.TweetsToolbox.bmp")]
    [Designer(typeof(SendTweetWithMediaDesigner))]
    [Description("Updates the authenticating user's current status and attaches media for upload.")]
    public class SendTweetWithMedia : TwitterOperationInvoker<Status>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SendTweetWithMedia"/> class.
        /// </summary>
        public SendTweetWithMedia()
            : base("SendTweetWithMedia")
        {
            DisplayCoordinates = new InArgument<bool>(new CSharpValue<bool>("true"));
            PossiblySensitive = new InArgument<bool>(new CSharpValue<bool>("false"));
        }


        /// <summary>
        /// The text of your status update, typically up to 140 characters. 
        /// <remarks>
        /// Required Argument
        /// </remarks>
        /// </summary>
        /// <value>
        /// The text of your status update
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("The text of your status update")]
        [RequiredArgument]
        public InArgument<string> Text { get; set; }

        /// <summary>
        /// Media Path (Local, unc or http Path)
        /// <remarks>
        /// Required Argument
        /// </remarks>
        /// </summary>
        /// <value>
        /// The media path.
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("Media Path (Local, unc or http Path)")]
        [RequiredArgument]
        public InArgument<string> MediaPath { get; set; }

        /// <summary>
        /// Media Name
        /// </summary>
        /// <value>
        /// MediaName
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("Media Name")]
        public InArgument<string> MediaName { get; set; }

        /// <summary>
        /// The ID of an existing status that the update is in reply to.
        /// </summary>
        /// <value>
        /// The ID of an existing status that the update is in reply to.
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("The ID of an existing status that the update is in reply to.")]
        public InArgument<string> InReplyToStatusID { get; set; }

        /// <summary>
        /// The latitude of the location this tweet refers to.
        /// </summary>
        /// <value>
        /// The latitude.
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("The latitude of the location this tweet refers to.")]
        public InArgument<string> Latitude { get; set; }

        /// <summary>
        /// The longitude of the location this tweet refers to.
        /// </summary>
        /// <value>
        /// The longitude.
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("The longitude of the location this tweet refers to.")]
        public InArgument<string> Longitude { get; set; }

        /// <summary>
        /// A place in the world. These IDs can be retrieved from ReverseGeoCode.
        /// </summary>
        /// <value>
        /// The place ID.
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("A place in the world. These IDs can be retrieved from ReverseGeoCode.")]
        public InArgument<string> PlaceID { get; set; }

        /// <summary>
        /// Whether or not to put a pin on the exact coordinates a tweet has been sent from.
        /// <remarks>
        /// Required Argument
        /// </remarks>
        /// </summary>
        /// <value>
        /// The display coordinates.
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("Whether or not to put a pin on the exact coordinates a tweet has been sent from.")]
        [RequiredArgument]
        public InArgument<bool> DisplayCoordinates { get; set; }

        /// <summary>
        ///  Set to true for content which may not be suitable for every audience.
        ///  <remarks>Required Argument</remarks>
        /// </summary>
        /// <value>
        ///   <c>true</c> if [trim user]; otherwise, <c>false</c>.
        /// </value>
        [Browsable(true)]
        [Category("Parameters")]
        [Description("Set to true for content which may not be suitable for every audience.")]
        [RequiredArgument]
        public InArgument<bool> PossiblySensitive { get; set; }

        /// <summary>
        /// Gets or sets the request stream.
        /// </summary>
        /// <value>
        /// The request stream.
        /// </value>
         [Browsable(false)]
        public InArgument<Stream> RequestStream { get; set; }

        /// <summary>
        /// Caches the metadata.
        /// </summary>
        /// <param name="metadata">The metadata.</param>
        protected override void CacheMetadata(System.Activities.NativeActivityMetadata metadata)
        {
            RuntimeArgument textArgument = new RuntimeArgument("Text", typeof(string), ArgumentDirection.In, true);
            metadata.Bind(Text, textArgument);
            metadata.AddArgument(textArgument);

            RuntimeArgument mediaPathArgument = new RuntimeArgument("MediaPath", typeof(string), ArgumentDirection.In, true);
            metadata.Bind(MediaPath, mediaPathArgument);
            metadata.AddArgument(mediaPathArgument);

            RuntimeArgument mediaNameArgument = new RuntimeArgument("MediaName", typeof(string), ArgumentDirection.In, false);
            metadata.Bind(MediaName, mediaNameArgument);
            metadata.AddArgument(mediaNameArgument);

            RuntimeArgument inReplyToStatusIDArgument = new RuntimeArgument("InReplyToStatusID", typeof(string), ArgumentDirection.In, false);
            metadata.Bind(InReplyToStatusID, inReplyToStatusIDArgument);
            metadata.AddArgument(inReplyToStatusIDArgument);

            RuntimeArgument latitudeArgument = new RuntimeArgument("Latitude", typeof(string), ArgumentDirection.In, false);
            metadata.Bind(Latitude, latitudeArgument);
            metadata.AddArgument(latitudeArgument);

            RuntimeArgument longitudeArgument = new RuntimeArgument("Longitude", typeof(string), ArgumentDirection.In, false);
            metadata.Bind(Longitude, longitudeArgument);
            metadata.AddArgument(longitudeArgument);

            RuntimeArgument placeIDArgument = new RuntimeArgument("PlaceID", typeof(string), ArgumentDirection.In, false);
            metadata.Bind(PlaceID, placeIDArgument);
            metadata.AddArgument(placeIDArgument);

            RuntimeArgument displayCoordinatesArgument = new RuntimeArgument("DisplayCoordinates", typeof(bool), ArgumentDirection.In, true);
            metadata.Bind(DisplayCoordinates, displayCoordinatesArgument);
            metadata.AddArgument(displayCoordinatesArgument);

            RuntimeArgument possiblySensitiveArgument = new RuntimeArgument("PossiblySensitive", typeof(bool), ArgumentDirection.In, true);
            metadata.Bind(PossiblySensitive, possiblySensitiveArgument);
            metadata.AddArgument(possiblySensitiveArgument);

            base.CacheMetadata(metadata);
        }

        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        protected override void Execute(System.Activities.NativeActivityContext context)
        {
            TweetWithMediaRequest request = new TweetWithMediaRequest()
            {
                DisplayCoordinates = DisplayCoordinates.Get(context),
                InReplyToStatusID = InReplyToStatusID.Get(context),
                Latitude = Latitude.Get(context),
                Longitude = Longitude.Get(context),
                Media = new Media()
                {
                    Filename = MediaName.Get(context)
                },
                PlaceID = PlaceID.Get(context),
                PossiblySensitive = PossiblySensitive.Get(context),
                Text = Text.Get(context)
            };

            Uri mediaUri = null;
            try
            {
                mediaUri = new Uri(MediaPath.Get(context));
            }
            catch
            {
                throw new NotFoundException("Media Path is not a valid uri !", null);
            }
            request.Media.Content = GetMediaContent(mediaUri);

            RequestStream.Set(context, request.RequestStream);

            Parameters.Clear();

            Parameters.Add("stream", RequestStream);

            base.Execute(context);
        }

        private byte[] GetMediaContent(Uri mediaUri)
        {
            switch (mediaUri.Scheme.ToLower())
            {
                case "file":
                    if(!File.Exists(mediaUri.LocalPath))
                        throw new NotFoundException(String.Format("Media {0} doesn't exist", mediaUri), null);
                    return File.ReadAllBytes(mediaUri.LocalPath);
                case "http":
                case "https":
                    using (MemoryStream ms = new MemoryStream())
                    {
                        WebRequest.Create(mediaUri.ToString()).GetResponse().GetResponseStream().CopyTo(ms);
                        return ms.ToArray();
                    }
                default:
                    throw new NotFoundException(
                        String.Format("Media Scheme {0} Not Supported", mediaUri.Scheme), null);
            }
        }
    }
}
